#include <iostream>
#include <string>
#include <fstream>
#include <unordered_map>
#include <unistd.h>
#include "Log.hpp"

using namespace log_ns;
using namespace std;

const static string gpath = "./Dict.txt";
const string sep = ": "; // 每行数据的分隔符

class Dict
{
private:
    void LoadDict(const string &path)
    {
        ifstream in(path); // 读取文件的文件流
        if (!in.is_open())
        {
            LOG(FATAL, "open %s failed\n", path.c_str());
            exit(1);
        }

        string line;
        while (getline(in, line))
        {
            LOG(DEBUG, "load info:%s,success\n", line.c_str());
            if (line.size() == 0)
            {
                continue;
            }
            int pos = line.find(sep);
            if (pos == string::npos)
            {
                continue;
            }
            string key = line.substr(0, pos);
            if (key.size() == 0)
                continue;
            string value = line.substr(pos + sep.size());
            if (value.size() == 0)
                continue;
            _dict[key] = value;
        }
        LOG(INFO, "load %s success!\n", path.c_str());
        in.close();
    }

public:
    Dict(const string &path = gpath)
        : _dict_path(path)
    {
        LoadDict(path); // 加载指定文件的字典数据
    }

    string Translate(string key)
    {
        if (!_dict.count(key))
            return "None";
        return _dict[key];
    }

    ~Dict()
    {
    }

private:
    unordered_map<string, string> _dict;
    string _dict_path;
};